package Main.tool;

/**
 * Created with IntelliJ IDEA.
 * User: twobox
 * Date: 2020/3/14
 * Time: 20:51
 * Description: No Description
 */

public class ByteTool {
    static public int byteToInt(byte[] bytes) throws Exception {
        if (bytes.length>4)
            throw new Exception("数组长度大于4！");
        int result = 0;
        result = bytes[0] & 0xff;
        result = result << 8 | bytes[1] & 0xff;
        result = result << 8 | bytes[2] & 0xff;
        result = result << 8 | bytes[3] & 0xff;
        return result;
    }

    static public byte[] intToByte(int num) {
        byte[] bytes = new byte[4];
        //通过移位运算，截取低8位的方式，将int保存到byte数组
        bytes[0] = (byte)(num >>> 24);
        bytes[1] = (byte)(num >>> 16);
        bytes[2] = (byte)(num >>> 8);
        bytes[3] = (byte)num;
        return bytes;
    }

    static public byte[] manyToOne(byte[]... bytes) {
        int allLength = 0;
        for (int i=0; i<bytes.length; i++) {
            allLength += bytes[i].length;
        }
        byte[] result = new byte[allLength];
        allLength = 0;
        for (int i=0; i<bytes.length; i++) {
            System.arraycopy(bytes[i], 0, result, allLength, bytes[i].length);
            allLength += bytes[i].length;
        }
        return result;
    }
}

